const request = (num = 1) => {
    return new Promise((res, rej) => {
        setTimeout(() => {
            const arr = new Array(num).fill(num)
            const isSuccess = Boolean(Math.floor(Math.random() * 100) % 2)
            console.log('结果:', { success: isSuccess, data: arr })
            if (isSuccess) {
                res({ success: isSuccess, data: arr })
            } else {
                rej({ success: isSuccess, data: arr })
            }
        }, 4000 + Math.floor(Math.random() * 4000))
    })
}

const sendRequest = (requests, num) => {
    return new Promise((res) => {
        let currentRequest = 0
        const result = []
        let handleNum = 0
        let sum = 0
        const sendFun = (request, index) => {
            console.log('请求开始', index)
            request(Math.random()).then((res) => {
                result[index] = res
                handleNum++
                console.log('请求结束, success', index)
                return Promise.resolve(res)
            }).catch(err => {
                result[index] = err
                handleNum++
                console.log('请求结束 err', index)
                return Promise.resolve(err)
            }).then(() => {
                if (currentRequest < requests.length) {
                    sendFun(requests[currentRequest], currentRequest)
                    currentRequest++
                }
                if (handleNum >= requests.length) {
                    console.log('结束');
                    // console.log('result:', result);
                    res(result)
                }
            })
        }

        while (sum < num && sum < requests.length) {
            sendFun(requests[currentRequest], currentRequest)
            currentRequest++
            sum++
        }
    })
}

sendRequest([request, request, request, request, request, request, request, request, request, request], 3)